# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site: https://gitee.com/autumner/pythoncookbook.git 
@software: PyCharm Community Edition 
@file: sports_competition_analysis.py 
@time: 18-8-6 下午3:13
"""
'''
体育竞技分析-自顶向下设计
步骤：
步骤1：打印程序的介绍信息
def main():
    printIntro()
步骤2：获得程序运行需要的参数:probA, probB
def main():
    printIntro()
    probA, probB, n = getInputs()
步骤3：利用球员A和B的能力值probA和probB，模拟n次比赛
def main():
    printIntro()
    probA, probB, n = getInputs()
    winsA, winsB= simNGames(n, probA, probB)
步骤4：输出球员A和B获胜比赛的场次及概率
def main():
    printIntro()
    probA, probB, n = getInputs()
    winsA, winsB= simNGames(n, probA, probB)
    printSummary(winsA, winsB)
'''
from random import random


def printIntro():
    print('这个程序模拟两个选手A和B的体育竞技比赛')
    print('程序运行需要A和B的能力值(以0到1之间的小数表示)')


def getInputs():
    try:
        a = eval(input('请输入选手A的能力值(0~1):'))
        b = eval(input('请输入选手B的能力值(0~1):'))
        n = eval(input('模拟比赛的场次:'))
    except:
        print('输入参数非整数！请重新执行')
        exec('exit()')
    if a >= 1 or a < 0 or b >=1 or a < 0:
        print('选手能力值不在(0~1)范围内,请重新执行!')
        exec('exit()')
    return a, b, n


def simNGames(n, probA, probB):
    winsA, winsB = 0, 0
    for i in range(n):
        scoreA, scoreB = simOneGame(probA, probB)
        if scoreA > scoreB:
            winsA += 1
        else:
            winsB += 1
    return winsA, winsB


def simOneGame(probA, probB):
    scoreA, scoreB = 0, 0
    serving = 'A'
    while not gameOver(scoreA, scoreB):
        if serving == 'A':
            if random() < probA:
                scoreA += 1
            else:
                serving = 'B'
        else:
            if random() < probB:
                scoreB += 1
            else:
                serving = 'A'
    return scoreA, scoreB


def gameOver(a, b):
    return a == 11 or b == 11


def printSummary(winsA, winsB):
    n = winsA + winsB
    print('竞技分析开始,共模拟{}场比赛'.format(n))
    print('  选手A获胜{}场比赛,占比{:0.1%}'.format(winsA, winsA/n))
    print('  选手B获胜{}场比赛,占比{:0.1%}'.format(winsB, winsB/n))


def main():
    printIntro()
    probA, probB, n = getInputs()
    # print(probA, probB, n)
    winsA, winsB = simNGames(n, probA, probB)
    # print(winsA, winsB)
    printSummary(winsA, winsB)


if __name__ == '__main__':
    main()
